#include "registerwidget.h"
#include "ui_registerwidget.h"
#include <QDebug>

RegisterWidget::RegisterWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RegisterWidget),
    m_pUserManager(nullptr)
{
    ui->setupUi(this);
    connect(ui->btnRegister, &QPushButton::clicked, this, &RegisterWidget::onRegisterBtnClicked);
    connect(ui->btnBackToLogin, &QPushButton::clicked, this, [this]() { emit display(0); });
}

void RegisterWidget::setUserManager(UserManager* userManager)
{
    if (m_pUserManager) {
        m_pUserManager->deleteLater();
    }
    m_pUserManager = userManager;
}

void RegisterWidget::onRegisterBtnClicked()
{
    QString newUserName = ui->lineEditNewUserName->text().trimmed();
    QString newPassword = ui->lineEditNewPassword->text();
    QString newPasswordConfirm = ui->lineEditNewPasswordConfirm->text();
    QString newEmail = ui->lineEditNewEmail->text().trimmed();
    QString newPhone = ui->lineEditNewPhone->text().trimmed();

    // 输入验证
    if (newUserName.isEmpty() || newPassword.isEmpty() || newEmail.isEmpty() || newPhone.isEmpty()) {
        emit sendMessage("所有字段都必须填写");
        return;
    }

    if (newPassword != newPasswordConfirm) {
        emit sendMessage("两次输入的密码不一致");
        return;
    }

    if (!m_pUserManager) {
        emit sendMessage("系统错误：用户管理器未初始化");
        return;
    }

    auto result = m_pUserManager->registerUser(newUserName, newPassword, newEmail, newPhone, "user", "");

    if (result.first) {
        emit sendMessage("注册成功，请登录");
        emit display(0);
        clearInputFields();
    } else {
        handleRegisterError(result.second);
    }
}

void RegisterWidget::handleRegisterError(UserManager::UserError error)
{
    QString errorMsg;
    switch (error) {
        case UserManager::UserError::UserExists:
            errorMsg = "用户名已存在";
            break;
        case UserManager::UserError::InvalidInput:
            errorMsg = "输入无效，请检查字段";
            break;
        case UserManager::UserError::ConnectionError:
            errorMsg = "无法连接到服务器";
            break;
        default:
            errorMsg = "注册失败，请稍后再试";
            break;
    }
    emit sendMessage(errorMsg);
}

void RegisterWidget::clearInputFields()
{
    ui->lineEditNewUserName->clear();
    ui->lineEditNewPassword->clear();
    ui->lineEditNewPasswordConfirm->clear();
    ui->lineEditNewEmail->clear();
    ui->lineEditNewPhone->clear();
}

RegisterWidget::~RegisterWidget()
{
    delete ui;
}
